import random

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.views import View
from .utils.captcha.captcha import captcha
from django import  http
from users.models import  *
from users.sms.yuntongxun.ccp_sms import  CPP
# Create your views here.

class Register_view(APIView):
    def post(self,request):
        name = request.data.get("name")
        print(name)
        mobile = request.data.get("mobile")
        password1 = request.data.get("password1")
        password2 = request.data.get("password2")
        img = request.data.get("img")
        msg = request.data.get("msg")
        if not all([name,mobile,password1,password2,img,msg]):
            Response({"code":200,"msg":"请填写全部信息"})
        if password1 != password2 :
            Response({"code": 200, "msg": "请填写全部信息"})
        User.objects.create(username=name,mobile=mobile,password=password1)
        return Response({"code":200,"msg":"成功"})


class img_code_view(View):
    def get(self,request,a):
        text,image = captcha.generate_captcha()
        print(text)
        Is_msg.objects.filter(id=1).update(img=text)

        return http.HttpResponse(image,content_type="image/jpg")
        # return Response(text)
class Msg_CodeView(APIView):
    def post(self,request,mobile):
        img = request.data.get("img")

        sms_code = "%04d"%random.randint(0,9999)
        seng_msg = CPP().sendTemplateSMS(mobile,[sms_code,5],1)
        is_img = Is_msg.objects.get(id=1).img
        if img.lower() != is_img.lower():
            return Response({"code": 400, "msg": "图片验证码错误"})
        if seng_msg ==0:
            Is_msg.objects.filter(id=1).update(msg=sms_code)
            return Response({"code":200,"msg":"成功","data":sms_code})
        else:
            return Response({"code": 400, "msg": "失败"})

